import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import { addTab, timeLimit } from '@/utils/utils';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Input,
  Select,
  DatePicker,
  Button,
  Table,
} from 'antd';

import { TableListData } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { pathname } = window.location;
const { Item } = Form;

interface BrokenListProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: TableListData;
  INITINFO: any;
  screen: string;
}

interface BrokenListState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  rowId:number;
}

@connect(({
  brokenList: { dataInfo },
  common: { INITINFO },
}: any) => ({
  dataInfo,
  INITINFO,
}))

class BrokenListElem extends Component<BrokenListProps, BrokenListState> {
  columns = [
    { title: '编号', dataIndex: 'code' },
    { title: '名称', dataIndex: 'name' },
    { title: '软件版本', dataIndex: 'softVersion' },
    { title: '硬件版本', dataIndex: 'hwareVersion' },
    { title: '结构版本', dataIndex: 'structVersion' },
    { title: '运营状态', render: () => '运营' },
    { title: '断网次数', dataIndex: 'count' },
    {
      title: '操作',
      render: (val: number, record: any) => (
        <span
          className="operLink"
          onClick={() => this.handleShowBroken(record.code)}
        >
          详情
        </span>
      ),
    },
  ]

  state: BrokenListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query }, screen } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    this.fetchAction('common/fetchLogisList');
    this.fetchAction('common/fetchGardenList');

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      searchValues: {
        startTime, endTime, ...others
      },
    } = this.state;
    if (startTime) {
      others.start_end_time = [moment(startTime), endTime ? moment(endTime) : ''];
    } else {
      others.start_end_time = [moment(startTime), ''];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  };

  fetchDataValues = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'brokenList/fetch',
      payload: this.getQueryParams(),
    });
  }

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    if (!searchValues.startTime) {
      params.startTime = moment().startOf('day').format('YYYY-MM-DD');
      params.endTime = '';
    }

    return params;
  };

  /**
   * 查看详情
   */
  handleShowBroken = (code: number) => {
    const { searchValues: { startTime, endTime } } = this.state;
    const query = { code, startTime, endTime };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${code}`,
      url: `/basic/cabinetManagement/list/brokenDetail?${qs.stringify(query)}`,
    });
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, fieldsValue) => {
      if (errors) return;

      if (fieldsValue.start_end_time) {
        if (fieldsValue.start_end_time[0]) {
          fieldsValue.startTime = moment(fieldsValue.start_end_time[0]).format('YYYY-MM-DD');
        } else {
          fieldsValue.startTime = '';
        }

        if (fieldsValue.start_end_time[1]) {
          fieldsValue.endTime = moment(fieldsValue.start_end_time[1]).format('YYYY-MM-DD');
        } else {
          fieldsValue.endTime = '';
        }
      } else {
        fieldsValue.startTime = '';
        fieldsValue.endTime = '';
      }
      delete fieldsValue.start_end_time;

      const query = { pageIndex: 1, ...fieldsValue };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '断网统计',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '断网统计',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '断网统计',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0 ? typeName : `brokenList/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const {
      pageIndex, pageSize,
    } = this.state;

    const {
      dataInfo,
      INITINFO: { logisList, gardenList },
      form: { getFieldDecorator },
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Item label="起止时间" colon={false}>
                  {getFieldDecorator('start_end_time', {
                    initialValue: [moment().startOf('day'), moment().endOf('day')],
                  })(
                    <RangePicker
                      showTime
                      placeholder={['开始时间', '截止时间']}
                      style={{ width: '100%' }}
                      format="YYYY-MM-DD"
                      disabledDate={timeLimit}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                        上月: [
                          moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                          moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                        ],
                      }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="柜体名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="硬件版本" colon={false}>
                  {getFieldDecorator('hwareVersion')(
                    <Select allowClear placeholder="请选择">
                      <Option value="1.0">1.0</Option>
                      <Option value="2.0">2.0</Option>
                      <Option value="2.7">2.7</Option>
                      <Option value="3.0">3.0</Option>
                      <Option value="4.0">4.0</Option>
                      <Option value="5.0">5.0</Option>
                      <Option value="6.0">6.0</Option>
                      <Option value="7.0">7.0</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option key={item.id} value={String(item.id)}>{item.name}</Option>
                      ))
                      }
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="柜体编号" colon={false}>
                  {getFieldDecorator('code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="小区/学校" colon={false}>
                  {getFieldDecorator('gardenId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option key={item.id} value={String(item.id)}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>

              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            className="statementTable tableHeihgt60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<BrokenListProps>()(BrokenListElem);
